package com.qtummatrix.controller;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.qtummatrix.entity.EmpinfoEntity;
import com.qtummatrix.entity.OrganizationEntity;
import com.qtummatrix.service.AuthotityManagerService;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * create by Gongshiyong  2019-11-21 20:02
 */
@Controller("authotityAction")
public class AuthotityManagerController extends ActionSupport implements ModelDriven<EmpinfoEntity> {

    @Autowired
    private AuthotityManagerService authotityManagerService;

    private EmpinfoEntity empinfoEntity = new EmpinfoEntity();

    private String rolePermission;

    public String getRolePermission() {
        return rolePermission;
    }

    public void setRolePermission(String rolePermission) {
        this.rolePermission = rolePermission;
    }

    private Map<String, Object> info = new HashMap<String, Object>();

    public EmpinfoEntity getEmpinfoEntity() {
        return empinfoEntity;
    }

    public void setEmpinfoEntity(EmpinfoEntity empinfoEntity) {
        this.empinfoEntity = empinfoEntity;
    }

    public Map<String, Object> getInfo() {
        return info;
    }

    /**
     * 获取使用者列表信息
     *
     * @return
     */
    public String getUserList() {
        //条件
        String tel = empinfoEntity.getTel();//账号
        String username = empinfoEntity.getUsername();
        String rooleid = empinfoEntity.getRooleid();
        int bankid = empinfoEntity.getBankid();
        int organization = empinfoEntity.getOrganization();
        int state = empinfoEntity.getState();

        HttpServletRequest request = ServletActionContext.getRequest();
        //当前页码
        int pageNo = Integer.parseInt(request.getParameter("pageNo")) - 1;
        //页面的条数
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));//默认10条数据

        //查询使用者信息
        List<Map<String, Object>> userList = authotityManagerService.getUserList(tel, username, rooleid, bankid,
                organization, state, pageNo, pageSize);
        //获取使用者的记录数
        Integer userSize = authotityManagerService.getUserSize(tel, username, rooleid, bankid, organization, state);
        info.put("list", userList);
        // 返回的数据列表
        // 当前页数
        info.put("pageNum", pageNo + 1);
        // 总页数
        int pages = userSize % pageSize == 0 ? userSize / pageSize : userSize / pageSize + 1;
        info.put("pages", pages);
        // 总条数
        info.put("total", userSize);

        return SUCCESS;
    }

    public String getUserListBySearch() {

        System.out.println("getUserListBySearch...");
        return SUCCESS;
    }

    /**
     * 重置用户的密码
     *
     * @return
     */
    public String updateResetUserPassword() {
        int id = empinfoEntity.getId();

        System.out.println("重置密码...");
        int i = authotityManagerService.resetUserPassword(id);
        if (i == 1) {//重置成功
            info.put("resetResult", "1");
        } else {
            info.put("resetResult", "0");
        }
        return SUCCESS;
    }

    /**
     * 更改用户的状态
     *
     * @return
     */
    public String userOpenEdit() {
        int id = empinfoEntity.getId();
        System.out.println("更改用户状态...");
        int i = authotityManagerService.userOpenEdit(id);
        if (i == 1) {
            info.put("updateResult", "1");
        } else {
            info.put("updateResult", "0");
        }
        return SUCCESS;
    }

    /**
     * 验证手机号是否存在
     *
     * @return
     */
    public String getValidatePhone() {
        String tel = empinfoEntity.getTel();
        System.out.println("验证用户手机号...");
        int i = authotityManagerService.validatePhone(tel);
        if (i == 1) {
            info.put("validateResult", "账号正常！");
        } else if (i == 2) {
            info.put("validateResult", "账号禁用，联系管理员启用！");
        } else {
            info.put("validateResult", "账号不存在！");
        }
        return SUCCESS;
    }

    /**
     * 登录验证
     *
     * @return
     */
    public String getUserLoginValidate() {
        String tel = empinfoEntity.getTel();
        String password = empinfoEntity.getPassword();
        EmpinfoEntity empinfoEntity = authotityManagerService.UserLoginValidate(tel, password);
        if (empinfoEntity == null) {
            info.put("userinfo", "登录失败");
            return ERROR;
        } else {
            HttpServletResponse response = ServletActionContext.getResponse();
            HttpServletRequest request = ServletActionContext.getRequest();
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    cookie.setMaxAge(0);//将cookie设置为0，表示删除
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
            }

            //登陆成功保存用户信息到cookie中
            info.put("userinfo", "登录成功");
            //登陆成功后，将用户信息（用户名，当前登录时间，和当前用户的权限）
            Map<String, String> map = authotityManagerService.getCurrentUserPerssion(tel);
            String permission = map.get("permission");//权限
            String roleName = map.get("roleName");//角色名
            String userName = tel;//手机号

            //实例化cookie存储信息
            Cookie cookie1 = new Cookie("roleName", roleName);//角色名
            Cookie cookie2 = new Cookie("permission", permission);//权限
            Cookie cookie3 = new Cookie("tel", tel);//手机号
            //添加Cookie到客户端

            response.addCookie(cookie1);
            response.addCookie(cookie2);
            response.addCookie(cookie3);

            return "userinfo";
        }
    }

    /**
     * 验证添加使用者的手机号是否存在
     *
     * @return
     */
    public String getValidateaddUserTel() {
        String tel = empinfoEntity.getTel();
        int i = authotityManagerService.ValidateaddUserTel(tel);
        if (i > 0) {
            info.put("validateaddTel", "验证失败，账号已存在！");
        } else {
            info.put("validateaddTel", "验证通过！");
        }
        return SUCCESS;
    }

    /**
     * 获取所有所属银行和所属机构和角色
     *
     * @return
     */
    public String getAllComOrgRole() {
        List<OrganizationEntity> allComName = authotityManagerService.getAllCompany();
        List<Map<String, Object>> allBankName = authotityManagerService.getAllBankName();
        List<Map<String, Object>> allRole = authotityManagerService.getAllRole();
        info.put("allComName", allComName);//机构
        info.put("allBankName", allBankName);//银行
        info.put("allRoleName", allRole);//角色
        return SUCCESS;
    }

    /**
     * 添加使用者信息
     *
     * @return
     */
    public String getAddUserInfo() {
        String username = empinfoEntity.getUsername();
        String password = empinfoEntity.getPassword();
        String tel = empinfoEntity.getTel();
        int bankid = empinfoEntity.getBankid();
        String rooleid = empinfoEntity.getRooleid();
        String roleid = rooleid.substring(0, rooleid.length() - 1);
        Date entryTime = empinfoEntity.getEntryTime();
        int organization = empinfoEntity.getOrganization();
        String email = empinfoEntity.getEmail();
        String linkmanname = empinfoEntity.getLinkmanname();
        String linkmantel = empinfoEntity.getLinkmantel();
        String companytel = empinfoEntity.getCompanytel();

        int i = authotityManagerService.AddUserInfo(username, password, tel, bankid, roleid, entryTime, organization
                , email, linkmanname, linkmantel, companytel);
        info.put("addUserResult", "添加成功");

        return SUCCESS;
    }


    public EmpinfoEntity getModel() {
        return empinfoEntity;
    }
}
